package org.deri.socializer.activities.map;

import java.util.ArrayList;
import java.util.Iterator;

import org.deri.socializer.NotificationPanel;

import org.deri.socializer.SocializerApplication;
import org.deri.socializer.activities.start.StartActivity;
import org.deri.socializer.com.http.HTTPClient;
import org.deri.socializer.com.http.Surfer;
import org.deri.socializer.com.http.Walker;
import org.deri.socializer.com.http.Website;
import org.deri.socializer.com.xmpp.XmppClient;
import org.deri.socializer.com.xmpp.XmppMessageHandler;
import org.deri.vor.R;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ToggleButton;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;

public class GoogleMapsActivity extends MapActivity implements XmppMessageHandler {


	
	private boolean created = false;
	
	private SocializerApplication app;
	private MapView mapView;
	private NotificationPanel popupPanel;
	private HTTPClient httpClient;
	private XmppClient xmppClient;
	public XmppClient getXmppClient() {
		return xmppClient;
	}





	private WebsiteLocationsOverlay websiteLocationsOverlay;
	private WalkerLocationsOverlay walkerLocationsOverlay;
	private SurferLocationsOverlay surferLocationsOverlay;
	
	private int zoomLevel;
	private GeoPoint center;
	
	private boolean showCloseWebsites = false;
	private boolean showCloseSurfers = false;
	private boolean showCloseWalkers = false;
	
	private Handler handler = new Handler();

	public static final int viewCheckingDelay = 500; // in ms

	
	
	private Runnable viewChangeChecker = new Runnable() {
	    public void run(){
	    	checkViewChange();
	    	handler.removeCallbacks(viewChangeChecker); 				// remove the old callback
	        handler.postDelayed(viewChangeChecker, viewCheckingDelay); 	// register a new one
	    }
	};

	
	public void onCreate(Bundle savedInstanceState) {
		System.out.println("GoogleMapsActivity.onCreate");
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.socializer_map);
	    
	    this.mapView = (MapView) findViewById(R.id.mapViewID);
	    this.mapView.setBuiltInZoomControls(true);
	    this.app = (SocializerApplication)getApplicationContext();
        this.xmppClient = this.app.getXMPPClient();
        this.xmppClient.setXMPPMessageHandler(this);
	    this.httpClient = this.app.getHTTPClient();
	    this.popupPanel = new NotificationPanel(this.app, this, R.layout.mappopup, R.id.relativeLayoutMap);
	    
	    initOverlays();
	    //initLocationManager();
	    initToggleButtons();
	    
        
	    share_button();
        
        created = true;
	}
	

	
	
	private void initOverlays() {

		Drawable redPinIcon = getResources().getDrawable(R.drawable.webpage_icon);
		redPinIcon.setBounds(0, 0, redPinIcon.getIntrinsicWidth(), redPinIcon.getIntrinsicHeight());
 		this.websiteLocationsOverlay = new WebsiteLocationsOverlay(redPinIcon, this);
	
 		Drawable walkerIcon = getResources().getDrawable(R.drawable.walker_icon);
 		walkerIcon.setBounds(0, 0, walkerIcon.getIntrinsicWidth(), walkerIcon.getIntrinsicHeight());
 		this.walkerLocationsOverlay = new WalkerLocationsOverlay(walkerIcon, this);
 		
 		Drawable surferIcon = getResources().getDrawable(R.drawable.surfer_icon);
 		surferIcon.setBounds(0, 0, surferIcon.getIntrinsicWidth(), surferIcon.getIntrinsicHeight());
 		this.surferLocationsOverlay = new SurferLocationsOverlay(surferIcon, this);
 		
 		this.mapView.getOverlays().add(websiteLocationsOverlay);
 		this.mapView.getOverlays().add(walkerLocationsOverlay);
 		this.mapView.getOverlays().add(surferLocationsOverlay);
	}
	
	public MapView getMap() {
		return this.mapView;
	}
	
	public SocializerApplication getApp() {
		return this.app;
	}
	

	
	private void initToggleButtons() {
		
		ToggleButton toggleButtonWebsites = (ToggleButton) findViewById(R.id.buttonMapSites);
		toggleButtonWebsites.setOnClickListener(new OnClickListener() {
	            @Override
	            public void onClick(View v) {
	                 toggleCloseWebsitesOverlay();
	            }
	        });
		ToggleButton toggleButtonWalkers = (ToggleButton) findViewById(R.id.buttonMapWalker);
		toggleButtonWalkers.setOnClickListener(new OnClickListener() {
	            @Override
	            public void onClick(View v) {
	                 toggleCloseWalkersOverlay();
	            }
	        });
		ToggleButton toggleButtonSurfers = (ToggleButton) findViewById(R.id.buttonMapSurfer);
		toggleButtonSurfers.setOnClickListener(new OnClickListener() {
	            @Override
	            public void onClick(View v) {
	                 toggleCloseSurfersOverlay();
	            }
	        });
	}
	
	private void toggleCloseWebsitesOverlay() {
		ToggleButton toggleButtonWebsites = (ToggleButton) findViewById(R.id.buttonMapSites);
		if (toggleButtonWebsites.isChecked()) {
			this.showCloseWebsites = true;
			this.showCloseWebsites();
		} else {
			this.showCloseWebsites = false;
			this.clearWebsiteLocationsOverlay();
		}
	}
	
	private void toggleCloseWalkersOverlay() {
		ToggleButton toggleButtonWalkers = (ToggleButton) findViewById(R.id.buttonMapWalker);
		if (toggleButtonWalkers.isChecked()) {
			this.showCloseWalkers = true;
			this.showCloseWalkers();
		} else {
			this.showCloseWalkers = false;
			this.clearWalkerLocationsOverlay();
		}
	}
	
	private void toggleCloseSurfersOverlay() {
		ToggleButton toggleButtonSurfers = (ToggleButton) findViewById(R.id.buttonMapSurfer);
		if (toggleButtonSurfers.isChecked()) {
			this.showCloseSurfers = true;
			this.showCloseSurfers();
		} else {
			this.showCloseSurfers = false;
			this.clearSurferLocationsOverlay();
		}
	}

	
	private void clearWebsiteLocationsOverlay() {
		this.websiteLocationsOverlay.clear();
		this.mapView.invalidate();
	}
	
	private void clearWalkerLocationsOverlay() {
		this.walkerLocationsOverlay.clear();
		this.mapView.invalidate();
	}
	
	private void clearSurferLocationsOverlay() {
		this.surferLocationsOverlay.clear();
		this.mapView.invalidate();
	}
	
	
	public NotificationPanel getPopupPanel() {
		return popupPanel;
	}


	protected void showCloseWebsites() {
		if (!this.showCloseWebsites)
			return;
		
		clearWebsiteLocationsOverlay();
	
		DisplayDimensions displayDimensions = DisplayDimensions.getDisplayDimensions(this.mapView);
			
		ArrayList<Website> websites = this.httpClient.getCloseWebsites("http://" + SocializerApplication.DEFAULT_HTTP_HOST + "/weblocator/do_command.php", displayDimensions, 10);
		Iterator<Website> websiteIter = websites.iterator();
		Website website;
		while (websiteIter.hasNext()) {
			website = websiteIter.next();
			GeoPoint point = new GeoPoint(website.getLatitude(), website.getLongitude());
			WebsiteOverlayItem websiteItem = new WebsiteOverlayItem(point, null, null, website);
			this.websiteLocationsOverlay.addItem(websiteItem);
		}
		this.mapView.postInvalidate();
	}
	
	
	protected void showCloseWalkers() {	
		if (!this.showCloseWalkers)
			return;
		
		clearWalkerLocationsOverlay();
	
		DisplayDimensions displayDimensions = DisplayDimensions.getDisplayDimensions(this.mapView);

		ArrayList<Walker> walkers = this.httpClient.getCloseWalkers("http://" + SocializerApplication.DEFAULT_HTTP_HOST + "/weblocator/do_command.php", displayDimensions, 10);
		Iterator<Walker> walkerIter = walkers.iterator();
		Walker walker;
		while (walkerIter.hasNext()) {
			walker = walkerIter.next();
			GeoPoint point = new GeoPoint(walker.getLatitude(), walker.getLongitude());
			WalkerOverlayItem walkerItem = new WalkerOverlayItem(point, null , null, walker);
			this.walkerLocationsOverlay.addItem(walkerItem);
		}
		this.mapView.postInvalidate();
	}
	
	protected void showCloseSurfers() {	
		if (!this.showCloseSurfers)
			return;
		
		clearSurferLocationsOverlay();
		DisplayDimensions displayDimensions = DisplayDimensions.getDisplayDimensions(this.mapView);

		ArrayList<Surfer> surfers = this.httpClient.getCloseSurfers("http://" + SocializerApplication.DEFAULT_HTTP_HOST + "/weblocator/do_command.php", displayDimensions, 10);
		Iterator<Surfer> surferIter = surfers.iterator();
		Surfer surfer;
		while (surferIter.hasNext()) {
			surfer = surferIter.next();
			GeoPoint point = new GeoPoint(surfer.getLatitude(), surfer.getLongitude());
			SurferOverlayItem surferItem = new SurferOverlayItem(point, null, null, surfer);
			this.surferLocationsOverlay.addItem(surferItem);
		}
		this.mapView.postInvalidate();
	}
	

	
	
	public void checkViewChange() {
		boolean hasChanged = false;
		
		int currentZoomLevel = this.mapView.getZoomLevel();
		GeoPoint currentCenter = this.mapView.getMapCenter();
		
		if (currentZoomLevel != this.zoomLevel)
			hasChanged = true;
		if (!currentCenter.equals(this.center))
			hasChanged = true;
		
		this.zoomLevel = currentZoomLevel;
		this.center = currentCenter;
		
		if (hasChanged) {
			showCloseWebsites();
			showCloseWalkers();
			showCloseSurfers();
		}
	}
	
	
	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		boolean result = super.dispatchTouchEvent(event);
	    if (event.getAction() == MotionEvent.ACTION_UP) {
	    	//showCloseWebsites();
	    }
	    return result;

	}
	
	@Override
	protected void onResume()
	{
	    super.onResume();
	    handler.postDelayed(viewChangeChecker, viewCheckingDelay);
	    if (!created) {
	    	Intent intent = getIntent();
	    	finish();
	    	startActivity(intent);
	    }
	    SocializerApplication.runningActivities++;
	}

	@Override
	protected void onPause() {
	    super.onPause();
	    handler.removeCallbacks(viewChangeChecker); // stop the map from updating
	    created = false;
	    SocializerApplication.runningActivities--;
	}

	@Override
	protected void onDestroy() {
	    super.onDestroy();
	    this.app.checkActivityState();
	}

	@Override
	public void handleWebGroupChatPresence(Presence presence) {
		// TODO Auto-generated method stub
		
	}



	
	@Override
	public void handleGroupChatMessage(Message message) {
		this.app.lastMessage = message;
		GoogleMapsActivity.this.runOnUiThread(new Runnable() {
		    public void run() {
		    	openPanel();
		    }
		});
	}


	@Override
	public void handleChatMessage(Message message) {
		this.app.lastMessage = message;
		runOnUiThread(new Runnable() {
		    public void run() {
		    	openPanel();
		    }
		});

	}
	
	private void openPanel() {
	    this.popupPanel.hide();
        if (this.app.lastMessage.getType() == Message.Type.chat) {
        	this.popupPanel.showNewPrivateChatMessageNotification(this, this.xmppClient, true);
        } else {
        	this.popupPanel.showNewGroupChatMessageNotification(this, this.xmppClient, true);
        }
	}

	private void share_button(){
		Button button = (Button) findViewById(R.id.btnBack);
		button.setOnClickListener(ms_layout);

		// About Button OnClick
		button = (Button) findViewById(R.id.btnAbout);
		button.setOnClickListener(ms_layout);

		// Home Button OnClick
		button = (Button) findViewById(R.id.btnHome);
		button.setOnClickListener(ms_layout);
		
//		ImageView im  = (ImageView) findViewById(R.id.vor_icon);
//		im.setClickable(true);
//		im.setOnClickListener(ms_layout);
//
//		im = (ImageView) findViewById(R.id.nuig_icon);
//		im.setClickable(true);
//		im.setOnClickListener(ms_layout);
//
//		im = (ImageView) findViewById(R.id.deri_icon);
//		im.setClickable(true);
//		im.setOnClickListener(ms_layout);
	}
    
    
    private OnClickListener ms_layout	=	new OnClickListener(){

		@Override
		public void onClick(View v) {
			switch (v.getId()){
			case R.id.btnAbout  : { jump(72); break;}
			case R.id.btnHome 	: { jump(2); break;}
			case R.id.btnBack  	: { goback(); break;}
//			case R.id.vor_icon  : { jump(3); break;}
//			case R.id.deri_icon : { jump(19); break;}
//			case R.id.nuig_icon : { jump(40); break;}
			}
		}
    };

    private void jump(int page){
    	Intent i = new Intent();
    	i.putExtra("cl",page);
    	i.setClassName("org.deri.vor", "org.deri.vor.VovolOceanRaceActivity");
		startActivity(i);
		finish();
    }
    
    private void goback(){
    	Intent intent = new Intent(getApplicationContext(), StartActivity.class);
    	startActivity(intent);
    	finish();
    }
    


}

